import { ref } from 'vue'

// Popup统计数据
const stats = ref({
  todayCount: 0,
  totalCount: 0,
  pendingCount: 0
})

// 最近拦截的数据
const recentData = ref([])

// 插件状态
const pluginStatus = ref('运行中')

// 拦截规则
const interceptionRules = ref([])

let intervalId: number | null = null

// URL匹配函数
function isUrlMatch(url: string, pattern: string, matchType?: string): boolean {
  // 如果没有指定匹配类型，默认使用includes
  if (!matchType || matchType === 'includes') {
    return url.includes(pattern);
  }
  
  // 精确匹配
  if (matchType === 'exact') {
    // 移除查询参数后进行精确匹配
    const urlWithoutQuery = url.split('?')[0];
    return urlWithoutQuery === pattern;
  }
  
  // 前缀匹配
  if (matchType === 'startsWith') {
    return url.startsWith(pattern);
  }
  
  // 后缀匹配
  if (matchType === 'endsWith') {
    return url.endsWith(pattern);
  }
  
  // 正则表达式匹配
  if (matchType === 'regex') {
    try {
      const regex = new RegExp(pattern);
      return regex.test(url);
    } catch (e) {
      console.error('❌ 正则表达式错误:', pattern, e);
      return false;
    }
  }
  
  // 默认使用includes
  return url.includes(pattern);
}

// 从Chrome存储获取真实数据
const fetchRealData = async () => {
  try {
    console.log('开始获取真实数据...')
    // 获取拦截的请求数据（与原始插件兼容的格式）
    chrome.storage.local.get(['capturedRequests', 'interceptionRules'], (result) => {
      console.log('从存储中获取数据:', result)
      
      // 检查是否有数据
      if (!result) {
        console.log('存储结果为空')
        useFallbackData()
        return
      }
      
      // 确保stats.value存在且有正确的结构
      if (!stats.value || typeof stats.value !== 'object') {
        stats.value = {
          todayCount: 0,
          totalCount: 0,
          pendingCount: 0
        };
      } else {
        // 确保所有必需的属性都存在
        if (typeof stats.value.todayCount !== 'number') stats.value.todayCount = 0;
        if (typeof stats.value.totalCount !== 'number') stats.value.totalCount = 0;
        if (typeof stats.value.pendingCount !== 'number') stats.value.pendingCount = 0;
      }
      
      // 确保recentData.value存在且是数组
      if (!recentData.value || !Array.isArray(recentData.value)) {
        recentData.value = [];
      }
      
      // 确保pluginStatus.value存在
      if (!pluginStatus.value) {
        pluginStatus.value = '运行中';
      }
      
      // 确保interceptionRules.value存在且是数组
      if (!interceptionRules.value || !Array.isArray(interceptionRules.value)) {
        interceptionRules.value = [];
      }
      
      // 更新拦截规则（必须在处理数据之前完成）
      if (result.interceptionRules) {
        interceptionRules.value = Array.isArray(result.interceptionRules) ? result.interceptionRules : Object.values(result.interceptionRules)
        console.log('更新拦截规则:', interceptionRules.value)
      }
      
      if (!result.capturedRequests) {
        console.log('没有找到capturedRequests键')
        useFallbackData()
        return
      }
      
      const interceptedData: any[] = Array.isArray(result.capturedRequests) ? result.capturedRequests : []
      console.log('拦截数据数组长度:', interceptedData.length)
      console.log('拦截数据内容:', interceptedData)
      
      if (interceptedData.length === 0) {
        console.log('拦截数据为空数组')
        useFallbackData()
        return
      }
      
      console.log('获取到拦截数据:', interceptedData.length, '条')
      
      // 计算总数
      stats.value.totalCount = interceptedData.length
      
      // 计算今日数量
      const today = new Date().toDateString()
      stats.value.todayCount = interceptedData.filter((item: any) => 
        new Date(item.timestamp).toDateString() === today
      ).length
      
      // 计算待同步数量（这里简化处理，实际应根据同步状态判断）
      stats.value.pendingCount = Math.min(10, Math.floor(interceptedData.length * 0.1))
      
      // 获取最近拦截的数据
      const sortedData = interceptedData
        .sort((a: any, b: any) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
        .slice(0, 5)
      
      console.log('最近数据:', sortedData)
      console.log('当前拦截规则:', interceptionRules.value)
      
      recentData.value = sortedData.map((item: any) => {
        console.log('处理数据项:', item)
        // 优先使用数据中的dataType字段
        if (item.dataType) {
          let source = '📦 未知数据'
          let type = item.dataType
          
          // 根据数据类型设置显示名称
          switch (item.dataType) {
            case 'bank':
              source = '🏦 银行流水'
              type = 'bank'
              break
            case 'sales_order':
              source = '📦 销售订单'
              type = 'order'
              break
            case 'purchase_order':
              source = '🛒 采购订单'
              type = 'order'
              break
            case 'incoming_invoice':
              source = '📥 进项发票'
              type = 'invoice'
              break
            case 'outgoing_invoice':
              source = '📤 销项发票'
              type = 'invoice'
              break
            case 'announcement':
              source = '📢 公告信息'
              type = 'announcement'
              break
            default:
              source = '📦 未知数据'
              type = 'other'
          }
          
          console.log('使用dataType字段:', item.dataType, '显示名称:', source)
          return {
            time: new Date(item.timestamp).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            }),
            source,
            type
          }
        }
        
        // 如果没有dataType字段，则根据拦截规则匹配数据类型
        let source = '📦 未知数据'
        let type = 'other'
        
        // 遍历拦截规则，找到匹配的规则
        for (const rule of interceptionRules.value) {
          console.log('检查规则:', rule.name, 'URL模式:', rule.urlPattern, '匹配类型:', rule.matchType, '启用状态:', rule.enabled)
          console.log('匹配URL:', item.url, '是否匹配:', isUrlMatch(item.url, rule.urlPattern, rule.matchType))
          
          if (rule.enabled !== false && item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
            source = rule.name || '📦 未知数据'
            // 根据规则的数据类型字段确定类型
            if (rule.dataType) {
              switch (rule.dataType) {
                case 'bank':
                  type = 'bank'
                  break
                case 'sales_order':
                  type = 'order'
                  break
                case 'purchase_order':
                  type = 'order'
                  break
                case 'incoming_invoice':
                  type = 'invoice'
                  break
                case 'outgoing_invoice':
                  type = 'invoice'
                  break
                case 'announcement':
                  type = 'announcement'
                  break
                default:
                  type = 'other'
              }
            } else {
              // 根据规则名称确定类型
              if (rule.name.includes('银行')) {
                type = 'bank'
              } else if (rule.name.includes('订单')) {
                type = 'order'
              } else if (rule.name.includes('发票')) {
                type = 'invoice'
              } else if (rule.name.includes('公告')) {
                type = 'announcement'
              } else {
                type = 'other'
              }
            }
            console.log('匹配到规则:', rule.name)
            break
          }
        }
        
        // 如果没有匹配到规则，使用默认值
        if (source === '📦 未知数据') {
          source = '🏦 银行流水'
          type = 'bank'
        }
        
        console.log('最终显示名称:', source, '类型:', type)
        return {
          time: new Date(item.timestamp).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          }),
          source,
          type
        }
      })
      
      console.log('更新后的recentData:', recentData.value)
    })
  } catch (error) {
    console.error('获取真实数据失败:', error)
    useFallbackData()
  }
}

// 使用模拟数据作为后备
const useFallbackData = () => {
  // 确保stats.value存在且有正确的结构
  if (!stats.value || typeof stats.value !== 'object') {
    stats.value = {
      todayCount: 0,
      totalCount: 0,
      pendingCount: 0
    };
  } else {
    // 确保所有必需的属性都存在
    if (typeof stats.value.todayCount !== 'number') stats.value.todayCount = 0;
    if (typeof stats.value.totalCount !== 'number') stats.value.totalCount = 0;
    if (typeof stats.value.pendingCount !== 'number') stats.value.pendingCount = 0;
  }
  
  // 确保recentData.value存在且是数组
  if (!recentData.value || !Array.isArray(recentData.value)) {
    recentData.value = [];
  }
  
  // 确保pluginStatus.value存在
  if (!pluginStatus.value) {
    pluginStatus.value = '运行中';
  }
}

// 同步数据
const syncData = () => {
  // 触发同步操作
  chrome.runtime.sendMessage({ action: 'syncData' }, (response) => {
    if (response && response.success) {
      console.log('数据同步已启动')
      // 重新获取数据
      fetchRealData()
    }
  })
}

// 初始化数据
const initPopupData = () => {
  fetchRealData()
  // 每5秒更新一次数据
  intervalId = window.setInterval(() => {
    fetchRealData()
  }, 5000) as unknown as number
}

// 清理定时器
const cleanup = () => {
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
}

export function usePopupData() {
  return {
    stats,
    recentData,
    pluginStatus,
    syncData,
    initPopupData,
    cleanup
  }
}